$NG.AllReady(function (
	page,
	{
		useDataIndexChange,
		useUpdateRow,
		useUpdateRows,
		useValuesChange,
		useBeforeClick,
		useClick,
	}
) {
	const userInfo = $NG.getUser();
	const mstform = $NG.getCmpApi("p_form_procurement_spare_m");
	const grid1 = $NG.getCmpApi("p_form_procurement_spare_d");
	// mstform.setHidden("u_phidkey",false); //设置隐藏
	const getItemValue = (itemName) => mstform.getItem(itemName).getValue();
	/**
	 *@default: 初始化
	 */
	if ($NG.getCmpApi("p_form_procurement_spare_m")) {
		getPtInfoByPhid();
		$NG.updateState((updater) => {
			updater.data.p_form_procurement_spare_m.setProps({
				phid_fcur: {
					value: 1,
					label: "人民币",
				},
				exchangerate: 1,
			});
		});

		if (page.oType == "add") {
            
			console.log("111")
			let generateKeyStr = generateKey().toString().replace(".", "");
			mstform.getItem("u_phidkey").setValue(generateKeyStr);
			$NG.execServer("GETuserdept", { phid: userInfo.userID }, (res) => {
				const datas = JSON.parse(res.data)[0].extendObjects;
				console.log(userInfo.userID, "userInfo.userID");

				console.log(datas, "GETuserdeptdatas");
				$NG.updateState((updater) => {
					updater.data.p_form_procurement_spare_m.setProps({
						u_applicant: {
							value: datas.hrid,
							label: datas.username,
						},
						u_apply_dept: {
							value: datas.dept_id,
							label: datas.deptname,
						},
					});
				});
			});
		}
	}
	/**
	 *@license: 	 //表头字段变化逻辑END	//表头字段变化逻辑BEGIN
	 */
	useValuesChange(async ({ args }) => {
		getPtInfoByPhid();
        setBillName()
		// let _arr = grid1.getRows();
		// let _json = [];
		// let lock = true;
		// setTimeout(async () => {
		// 	_arr.forEach((item) => {
		// 		console.log(`item`, item);
		// 		if (item.u_cost_pc) {
		// 			_json.push({
		// 				u_entity: "WKSSXMZZ",
		// 				u_account: item.u_cost_pc_EXName,
		// 				phid_fcur: mstform.getItem("phid_fcur").getValue(),
		// 			});
		// 		}
		// 	});
		// 	if (
		// 		_json.length == 0 ||
		// 		!mstform.getItem("u_budget_org_no").getValue() ||
		// 		!mstform.getItem("phid_fcur").getValue()
		// 	) {
		// 		lock = false;
		// 	}
		// 	const _data = {
		// 		billType: "WKSD",
		// 		phid_pc: mstform.getItem("phid_pc").getValue(),
		// 		bill_dt: mstform.getItem("bill_dt").getValue(),
		// 		detail: _json,
		// 	};
		// 	//  请求得到的数据
		// 	if (lock) {
		// 		await reqAmt(_data);
		// 		const _datas = resBody.data;
		// 		_datas.forEach((it) => {
		// 			_arr.forEach((item) => {
		// 				if (item.u_cost_pc_EXName == it.account) {
		// 					//TODO 在请求数据中查找并找到相应的数据进行对字段赋值
		// 					item.u_balance = it.balance;
		// 				}
		// 			});
		// 		});
		// 		
		// 	}
		// }, 300);
        grid1.refreshView();
	}, "p_form_procurement_spare_m.phid_pc");
    setBillName()
    function setBillName (){
        $NG.updateState((updater) => {
            updater.data.p_form_procurement_spare_m.setProps({
                bill_name:`${mstform.getItem("phid_pc").getText()=="undefined"?mstform.getItem("phid_pc").getText():""} 备品备件采购申请`
            });
        });
    }

	/**
	 *@function:带出项目信息
	 */
	function getPtInfoByPhid() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"getPtInfoByPhid",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
                    console.log('项目信息获取',res);
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas, "11111111111");
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_procurement_spare_m.setProps({
							// u_supply_att: datas.u_supply_att, //计划完工日期
							// u_supply_name: datas.u_supply_name, //计划竣工日期
							u_pc_no: datas.pc_no, //项目编码
							u_budget_org_name:datas.budget_org_name,
							u_budget_org_no:datas.budget_org_no,
							u_dept: {
								value: datas.dept_phid,
								label: datas.dept_name,
							},
							u_division: {
								//事业部or组织
								value: datas.org_phid,
								label: datas.org_name,
							},

							u_regional_center: {
								//区域中心
								value: datas.regional_center_phid,
								label: datas.regional_center_name,
							},
							u_product_line: {
								//产品线
								value: datas.midwife_phid,
								label: datas.midwife_name,
							},
                            u_budget_org_no:datas.budget_org_no,
                            u_budget_org_name:datas.budget_org_name
						});
					});
				}
			);
		}
		$NG.execServer(
			"projectSjbm",
			{ phid: `${mstform.getItem("phid_pc").getValue()}` },
			function (res) {
				try {
					const datas = JSON.parse(res.data)[0].extendObjects;
					//商机号
					mstform.getItem("u_sjh").setValue(datas.user_sjbm);
					//商机编码
					mstform.getItem("u_sjmc").setValue(datas.user_sjmc);
				} catch (error) { }
			}
		);
	}

	useValuesChange(({ args }) => {
		console.log(args, "u_budget_org");
	}, "p_form_procurement_spare_m.u_budget_org");
	/**
	 *@function:计算逻辑
	 */
	useUpdateRow(({ args }) => {
		console.log(args[0], "分包明细表 计算");
		let row = args[0];
		if (
			args[0].u_cost_pc_EXName &&
			mstform.getItem("phid_pc").getValue() &&
			mstform.getItem("u_budget_org").getValue() &&
			mstform.getItem("phid_fcur").getValue()
		) {
			const _maps = {
				billType: "WKSD",
				phid_pc: mstform.getItem("phid_pc").getValue(),
				bill_dt: mstform.getItem("bill_dt").getValue(),
				detail: [
					{
						u_entity: "WKSSXMZZ",
						u_account: args[0].u_cost_pc_EXName,
						phid_fcur: mstform.getItem("phid_fcur").getValue(),
					},
				],
			};
			// reqAmt(_maps);
		}
		computedV2(row);
		// 更新和刷新表格
		grid1.refreshView();
	}, "p_form_procurement_spare_d");
    cntDFilter()
    function cntDFilter() {
        $NG.updateUI(updater => updater.editGrid.p_form_procurement_spare_d.u_budget_account.setProps((p) => {
            return {
            ...p, editor: {
                ...p.editor,
                clientSqlFilter: { phid:'8570000000000393' },
            }
            };
        }));
        $NG.updateUI(updater => updater.editGrid.p_form_procurement_spare_d.u_cost_pc.setProps((p) => {
            return {
            ...p, editor: {
                ...p.editor,
                clientSqlFilter: { phid:'8570000000000393' },
            }
            };
        }));
    }
    useClick(async ({args})=>{
        setTimeout(()=>{
            const arr = grid1.getRows()
            arr.forEach(item=>{
                if(!item.u_balance){
                    reqAmt(item.u_budget_account,(_data)=>{
                        item.u_balance = _data.balance
                        grid1.refreshView()
                    })
                }
            })
            $NG.message("正在查询余额，请耐心等待~")
            $NG.message("正在查询余额，请耐心等待~")
            $NG.message("正在查询余额，请耐心等待~")
        },200)
    },"addrow")
	useUpdateRows(({ args }) => {
		let rows = args[0];
		let total = 0;

		rows.forEach((item) => {
            //默认剩余量
            item.u_syl = item.u_qty

            if(item.u_balance == undefined || item.u_balance == NaN || item.u_balance == null){
                console.log({...item},'ceshi ');
                setTimeout(()=>{
                    reqAmt(item.u_budget_account,(data)=>{
                        item.u_balance = data.balance
                        grid1.refreshView()
                    })
                },200)
            }
			total += item.u_amt_vat || 0; // 确保值存在且为数字
            item.u_budget_account = 8570000000000393
            item.u_budget_account_EXName = '服务费_维修材料耗用'
            item.u_cost_pc = 8570000000000393
            item.u_cost_pc_EXName = '服务费_维修材料耗用'
			if (item.itemid) {
				$NG.execServer("searchMasterP", { phid: item.itemid }, function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(datas, "xxxxxxxx");
					item.itemno = datas.itemno;
					item.spec = datas.spec;
					item.msunit = datas.msunit_phid;
					item.msunit_EXName = datas.msunit_name; //单位
					// item.u_item_sub = datas.res_bs_phid; //单位
					// item.u_item_sub_EXName = datas.res_bs_name; //单位
					grid1.refreshView();
				});
			}
		});
        grid1.refreshView()
		mstform.getItem("u_amt_vat").setValue(total);
		console.log("Total u_amt_vat:", total);

		// 更新和刷新表格
		// 带物料相信息;
	}, "p_form_procurement_spare_d");
	// TODO 单行更改触发请求，赋值到金额
	useDataIndexChange(async ({ args }) => {
        console.log(`费用项目监听测试`,args);
		if (args[0].u_budget_account_EXName) {
			await reqAmt(args[0].u_budget_account,(_data)=>{

                args[0].u_balance = _data.balance;
                grid1.refreshView();
            });
			
		}
	}, "u_budget_account");
	// useDataIndexChange(async ({ args }) => {
	// 	if (args[0].u_budget_account) {
	// 		const _maps = {
	// 			billType: "WKSD",
	// 			phid_pc: mstform.getItem("phid_pc").getValue(),
	// 			bill_dt: mstform.getItem("bill_dt").getValue(),
	// 			detail: [
	// 				{
	// 					u_entity: mstform.getItem("u_budget_org").getValue(),
	// 					u_account: args[0].u_budget_account,
	// 					phid_fcur: mstform.getItem("phid_fcur").getValue(),
	// 				},
	// 			],
	// 		};
	// 		const resBody = await reqAmt(_maps);
	// 		const _data = resBody.data[0];
	// 		args[0].u_balance = _data.balance;
	// 		grid1.refreshView();
	// 	}
	// }, "u_budget_account");

	function computedV2(rowItem) {
		const record = rowItem;

		// 提供默认值并确保为数字类型，防止字符串影响计算
		const u_qty = Number(record.u_qty) || 0; // 数量，默认为 0
		const u_vat_prc = Number(record.u_vat_prc) || 0; // 含税单价，默认为 0
		const u_tax_rate = Number(record.u_tax_rate) || 0; // 税率，默认为 0

		// 计算不含税单价
		const u_prc = u_vat_prc / (1 + u_tax_rate);

		// 计算字段值
		const u_amt_vat = u_qty * u_vat_prc; // 价税合计
		const u_amt = u_qty * u_prc; // 不含税金额
		const u_tax_amt = u_amt_vat - u_amt; // 税额
		const u_amt_vat_fc = u_amt_vat; // 价税合计（与 u_amt_vat 相同）

		// 更新 record 对象
		Object.assign(record, {
			u_prc,
			u_amt_vat,
			u_amt,
			u_tax_amt,
			u_amt_vat_fc,
		});
	}

    // 查询余额请求体
	async function reqAmt(km,fun) {
        if(!mstform.getItem("phid_pc").getValue()) return
        const _maps = {
            billType: "SD-0001",
            phid_pc: mstform.getItem("phid_pc").getValue(),
            bill_dt: mstform.getItem("bill_dt").getValue(),
            detail: [
                {
                    u_entity: "WKSSXMZZ",
                    u_account: km,
                    phid_fcur: mstform.getItem("phid_fcur").getValue(),
                },
            ],
        };
        console.log('请求参数检查',_maps);
		const resBody = await $NG.request.post({
			url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/fiCheckBalance",
			data: JSON.stringify(_maps),
			header: {
				"Content-Type": "application/json",
			},
		});
		console.log(`响应信息`, resBody);
        if(!resBody.IsOk){
            $NG.message(resBody.Message)
        }
        const _data = resBody.data[0];
        fun(_data)
	}
	useBeforeClick(async function ({ args }) {
		(function () { })();
		
		const _arr = grid1.getRows();
		const _index = [];
		let lock = true
		_arr.forEach((item, index) => {
			if ((Number(item.u_balance) || 0) < (Number(item.u_amt_vat) || 0)) {
				_index.push(index + 1);
			}
			if(item.u_balance == undefined || item.u_balance == null){
				lock = false
			}
		});
		console.log(`保存为`,lock);
		if(!lock){
			$NG.alert(`有明细余额为空！`)
			return false
		}
		if (_index.length !== 0) {
			$NG.alert(`明细中第 ${_index.join("、")} 行中，价税合计超出余额！！`);
			return false;
		}
		return true;
	}, "save");

	useClick((prop) => {
		setTimeout(() => {
			console.log("")
			$NG.execServer(
				"getPhidKey",
				{ phidkey: mstform.getItem("u_phidkey").getValue() },
				(res) => {
					mstform.getItem("u_phidkey").getValue()
					console.log(`响应信息datasssss??`);
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log("datas", datas);
					async function pushPhid() {
						const resBody = await $NG.request.post({
							url: "http://nginx.clouddev.hisense.com/sd/sdToFi/fiIntegration/pushBudgetPreoccupation",
							data: JSON.stringify({ phid: datas.phid }),
							header: {
								"Content-Type": "application/json",
							},
						});
						console.log(`响应信息1111`, resBody);
						return resBody;
					}
					pushPhid();
				}
			);
		}, 2000);
	}, "save");
});
function generateKey() {
	// 使用 Date.now() 获取当前时间戳
	let timestamp = Date.now();
	// 使用 Math.random() 生成一个随机数
	let random = Math.random();
	// 将时间戳和随机数组合，并转换为字符串
	let key = timestamp.toString() + random.toString();
	return key;
}
